<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\wxapp\controller;

use api\wxapp\controller\ApiBaseController;
use think\Db;
use api\wxapp\model\Address;
class AddressController extends ApiBaseController
{

    public function index()
    {
        $params = $this->getParam();
        $this->checkuid($params);
        $info = Address::where(['uid'=>$params['uid'],'status'=>1])->find();
        if(!$info){
            $info = Address::where('uid',$params['uid'])->all();
        }
        $this->success('请求成功!',$info);
    }  
    public function list()
    {
        $params = $this->getParam();
        $this->checkuid($params);
        $list = Address::where('uid',$params['uid'])->select();
        $this->success('请求成功!',$list);
    }
    public function add()
    {
        $params = $this->getParam();
        $this->checkuid($params);
        !isset($params['name']) ? $this->error('参数缺失!!!!') : '';
        !isset($params['address']) ? $this->error('参数缺失!!!!') : '';
        !isset($params['phone']) ? $this->error('参数缺失!!!!') : '';
        !isset($params['status']) ? $params['status'] = 2 : '';
        $params['addtime'] = $this->returnDateTime();
        if($params['status'] == 1){
            //设置了默认需要把 之前设置的默认地址  修改为非默认
            $info = Address::where(['uid'=>$params['uid'],'status'=>1])->find();
            if($info){
                Address::where('id',$info['id'])->update(['status'=>2]);
            }
        }
        $res = Address::insert($params);
        if($res){
            $this->success('请求成功!');
        }else{
            $this->error('请求失败!!!');
        }
    }
    public function put()
    {
        $params = $this->getParam();
        $this->checkid($params);
        $find = Address::get($params['id']);
        if(isset($params['status'])){
            if($params['status'] == 1){
                //设置了默认需要把 之前设置的默认地址  修改为非默认
                $info = Address::where(['uid'=>$find['uid'],'status'=>1])->find();
                if($info){
                    Address::where('id',$info['id'])->update(['status'=>2]);
                }
            }
        }
        $res = Address::update($params);
        if($res){
            $this->success('请求成功!');
        }else{
            $this->error('请求失败!!!');
        }
    }
    public function delete()
    {
        $params = $this->getParam();
        $this->checkid($params);
        $res = Address::destroy($params['id']);
        if($res){
            $this->success('请求成功!');
        }else{
            $this->error('请求失败!!!');
        }
    }
}
